package com.singzi.javaSenior.threads.threadPool.executor.example2;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);

        List<Future<Integer>> futureTaskList = new ArrayList<>();
        for(int i = 0;i < 10;i++){
            SumTask sumTask = new SumTask(i*100+1, (i+1)*100);
            Future<Integer> result = threadPoolExecutor.submit(sumTask);
            futureTaskList.add(result);
        }
        // 每隔50毫秒，轮询等待10个任务结束
        do {
            System.out.printf("Main: 已经完成多少个任务: %d\n",threadPoolExecutor.getCompletedTaskCount());
            for (int i=0; i<futureTaskList.size(); i++) {
                Future<Integer> result=futureTaskList.get(i);
                System.out.printf("Main: Task %d: %s\n",i,result.isDone());
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (threadPoolExecutor.getCompletedTaskCount()<futureTaskList.size());

        // 所有任务都已经结束了，综合计算结果
        int total = 0;
        for (int i=0; i<futureTaskList.size(); i++) {
            Future<Integer> result=futureTaskList.get(i);
            Integer sum=null;
            try {
                sum=result.get();
                total = total + sum;
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        System.out.printf("1-1000的总和:" + total);

        // 关闭线程池
        threadPoolExecutor.shutdown();

    }

}
class SumTask implements Callable{
    private int start;
    private int end;

    public SumTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for(int i = start;i <= end;i++){
            sum += i;
        }
        Thread.sleep(new Random().nextInt(100));
        System.out.println(Thread.currentThread().getName() + " :" + sum);
        return sum;
    }
}
